package com.app.toknow.Activity;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.app.toknow.R;

import com.app.toknow.Common.ConnectWSHelper;
import com.app.toknow.Common.ParseJsonUtil;
import com.app.toknow.Common.PrintAlertUtil;
import com.app.toknow.Common.SharedPreferencesUtil;
import com.app.toknow.Common.WSAPIMethodName;
import com.app.toknow.Entity.DBTable.T_UserInfo;
import com.app.toknow.MainActivity;
import com.app.toknow.View.CustomProgressDialog;
import com.app.toknow.View.ToastDialog;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "LoginActivity";
    private ToastDialog toastDialog;
    Button leftButton;
    Button rightButton;
    LinearLayout  navLayout;
    TextView titleText;
    RelativeLayout relativeLayout;
    Context context;
    private CustomProgressDialog loadingDialog = null;
    /** 第一种风格 **/
    private static final int LOADING_STYLE_01 = 1 ;
    /** 第二种风格 **/
    private static final int LOADING_STYLE_02 = 2 ;
    private static final int LOGIN_STATE_FAIL = 3;
    private static final int LOGIN_STATE_SUCCESS = 4;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initNavView();
        initContentView();
    }
    private void initNavView(){
        titleText = (TextView)findViewById(R.id.nav_title);
        titleText.setText("登陆");
    }

    private void initContentView(){
        findViewById(R.id.login_rootLayout).setOnClickListener(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.e("main","onkeydown");
        if(keyCode==KeyEvent.KEYCODE_BACK){
            finish();
        }
        return false;
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_rootLayout:
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                break;
            case R.id.button_login:
                EditText accountTV = (EditText)findViewById(R.id.edittext_account);
                EditText passwordTV = (EditText)findViewById(R.id.edittext_pas);
                boolean flag = true;
                if(accountTV.getText().toString().equals(""))
                {
                    toastDialog = ToastDialog.createToastConfig();
                    toastDialog.ToastShow(getApplicationContext(),"用户名为空");
                    flag = false;
                    return;
                }
                if(passwordTV.getText().toString().equals(""))
                {
                    toastDialog = ToastDialog.createToastConfig();
                    toastDialog.ToastShow(getApplicationContext(),"密码为空");
                    flag = false;
                    return;
                }
                if(flag)
                {
                    final String account = accountTV.getText().toString();
                    final String password = passwordTV.getText().toString();
                    loadingDialog = PrintAlertUtil.showProgressDialog(this, "正在登陆...");
                    Thread thread_login = new Thread(new Runnable() {

                        @Override
                        public void run()
                        {
                            Map<String, String> map = new HashMap<String, String>();
                            map.put("username", account);
                            Log.e("----username---",account);
                            map.put("password", password);
                            Log.e("----password---",password);
                            RequestWS(WSAPIMethodName.GET_USERID_LOGIN, ParseJsonUtil.JsonDataType.Object, map);
                        }
                    });
                    thread_login.start();
                }
                break;
            case R.id.register:
                Intent intent = new Intent(LoginActivity.this,RegisterOneActivity.class);
                startActivity(intent);
                break;
        }
    }

    /**
     * 执行异步任务
     *
     * @param params
     *            方法名+参数列表（哈希表形式）
     */
    public void RequestWS(Object... params) {
        new AsyncTask<Object, Object, String>() {
            private ParseJsonUtil.JsonDataType type;
            @Override
            protected String doInBackground(Object... params) {
                if (params != null && params.length == 3) {
                    type = (ParseJsonUtil.JsonDataType)params[1];
                    return ConnectWSHelper.GetResponse((String) params[0],
                            (Map<String, String>) params[2]);
                } else if (params != null && params.length == 1) {
                    return ConnectWSHelper.GetResponse((String) params[0], null);
                } else {
                    return null;
                }
            }

            protected void onPostExecute(String result) {
                Map<String, Object> list = ParseJsonUtil.parseJSONString(result,type);
                if (result != null) {
                    Log.e("----服务器回复的信息---",list.toString());
                    Message message = new Message();
                    Bundle bundle = message.getData();
                    bundle.putInt("STATE", Integer.parseInt(list.get("STATE").toString()));
                    bundle.putString("MESSAGE", (String) list.get("MESSAGE"));
                    String className = (String)list.get("CLASS");
                    bundle.putString("CLASS",className);
                    if(Integer.parseInt(list.get("STATE").toString()) == 1){
                        Class<?> objectClass = null;
                        switch (type){
                            case Object:
                                bundle.putInt("TYPE", ParseJsonUtil.JsonDataType.Object.ordinal());
                                //objectClass = Class.forName(ConfigManager.UtilityNameSpace + className);
                                //objectClass = ParseJsonUtil.SetBundelValue(list,"Entity")<objectClass>;
                                bundle.putSerializable("Entity", (Serializable)list.get("Entity"));
                                break;
                            case List:
                                break;
                            case Simple:
                                break;
                        }
                    }
//                    if(type == ParseJsonUtil.JsonDataType.Object)
//                    bundle.putInt("UserID", Integer.parseInt(list.get("UserID").toString()));
                    if(Integer.parseInt(list.get("STATE").toString()) == 1)
                        message.what = LOGIN_STATE_SUCCESS;
                    else
                        message.what = LOGIN_STATE_FAIL;
                    message.obj = "登陆";
                    mHandler.sendMessage(message);
                }
                else
                {
                    Message message = new Message();
                    Bundle bundle = message.getData();
                    bundle.putString("MESSAGE", "服务器请求失败");
//                    bundle.putString("result", result);
                    message.what = LOGIN_STATE_FAIL;
                    message.obj = "服务器请求失败";
                    mHandler.sendMessage(message);
                }
            };
        }.execute(params);
    }

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            switch (msg.what)
            {
                case LOGIN_STATE_SUCCESS:
                    Log.e("----LOGIN---","成功");
                    T_UserInfo userInfo = null;
                    //关闭对话框
                    PrintAlertUtil.dismissProgressDialog(loadingDialog);
                    Bundle bundle = msg.getData();
                    String className = bundle.getString("CLASS");
                    int Type = bundle.getInt("TYPE");

                    switch (ParseJsonUtil.JsonDataType.values()[Type])
                    {
                        case Object:
                            Serializable serializable = bundle.getSerializable("Entity");
                            userInfo = (T_UserInfo)serializable;
                            break;
                    }
                    if(userInfo !=null && userInfo.getUserID() > 0){
                        GoToNextActivity(userInfo.getUserID());
                    }
                    else{
                        toastDialog = ToastDialog.createToastConfig();
                        toastDialog.ToastShow(getApplicationContext(),"Data Convert Err");
                    }

                    break;

                case LOGIN_STATE_FAIL:
                    Log.e("----LOGIN---","失败");
                    String p = msg.getData().getString("MESSAGE");
                    PrintAlertUtil.dismissProgressDialog(loadingDialog);
                    toastDialog = ToastDialog.createToastConfig();
                    toastDialog.ToastShow(getApplicationContext(),p);
                    break;
            }
        }

    };
    void GoToNextActivity(int userID) {
        SharedPreferencesUtil.put(getApplicationContext(), "isLoginApp", true);
        SharedPreferencesUtil.put(getApplicationContext(),"LoginApp_UserID",userID);
        Intent intent;
        //去主页界面
        intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    }
}
